package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.hjq.base.BaseAdapter;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppAdapter;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.widget.SimpleAnimationDraweeView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2019/09/22
 *    desc   : 状态数据列表
 */
public final class RoomManagerSceneAdapter extends AppAdapter<SceneBean> {
    private boolean showFloorRoom = false;
    private boolean onlySeeCommonly = false;
    private boolean isSelectAct = true;
    private boolean isSingleSelect = false;
    private int bingingType = 0;

    private boolean showSettingButton = true;
    private List<SceneBean> allSceneData;
    private List<SceneBean> favouriteScene;
    private int maxSelectCount;
    private CountDownTimer timer;


    public void setMaxSelectCount(int maxSelectCount) {
        this.maxSelectCount = maxSelectCount;
    }

    public RoomManagerSceneAdapter setShowFloorRoom(boolean showFloorRoom) {
        this.showFloorRoom = showFloorRoom;
        notifyDataSetChanged();
        return this;
    }

    public RoomManagerSceneAdapter setOnlySeeCommonly(boolean onlySeeCommonly) {
        this.onlySeeCommonly = onlySeeCommonly;
        if (allSceneData!=null){
            if (onlySeeCommonly){
                setData(favouriteScene);
            }else {
                setData(allSceneData);
            }
        }
        notifyDataSetChanged();
        return this;
    }

    public RoomManagerSceneAdapter setSelectAct(boolean selectAct) {
        isSelectAct = selectAct;
        notifyDataSetChanged();
        return this;
    }

    public RoomManagerSceneAdapter setSingleSelect(boolean value) {
        isSingleSelect = value;
        return this;
    }

    public RoomManagerSceneAdapter setBingingType(int value) {
        bingingType = value;
        return this;
    }

    private Map<String, SceneBean> selected = new LinkedHashMap<>();

    public RoomManagerSceneAdapter(Context context) {
        super(context);
    }

    public void setTotalData(List<SceneBean> data){
        allSceneData = data;
        favouriteScene = getFavouriteScene();
        if (onlySeeCommonly){
            setData(favouriteScene);
        }else {
            setData(allSceneData);
        }
    }

    public void setShowSettingButton(boolean showSettingButton){
        this.showSettingButton = showSettingButton;
    }

    public List<SceneBean> getAllSceneData() {
        return allSceneData;
    }

    private List<SceneBean> getFavouriteScene(){
        List<SceneBean> commonBean = new ArrayList<>();
        for (SceneBean bean : allSceneData){
            if (bean.getIsFavourite()){
                commonBean.add(bean);
            }
        }
        return commonBean;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {
        private final View contentView;
        private final SimpleAnimationDraweeView icon;
        private final CheckBox checkbox;
        private final TextView tvName;
        private final TextView floorRoomName;
        private final ImageView tvCommonFlag;
        private final View vSetting;
        private final View vDelete;
        private final FrameLayout sortAction;
        private final TextView sortText;
        private final LinearLayout interruptView;
        private final TextView interruptTime;
        private final ImageView cancelImageView;
        private final LinearLayout addView;

        private ViewHolder() {
            super(R.layout.manager_scene_item);
            contentView = findViewById(R.id.content_view);
            icon = findViewById(R.id.icon_scene);
            checkbox = findViewById(R.id.checkbox);
            tvName = findViewById(R.id.tv_name);
            floorRoomName = findViewById(R.id.floor_room_name);
            tvCommonFlag = findViewById(R.id.tv_common_flag);
            checkbox.setOnClickListener(this);
            vSetting = findViewById(R.id.setting);
            vDelete = findViewById(R.id.delete);
            sortAction = findViewById(R.id.btn_sort_scene_action);
            sortText = findViewById(R.id.btn_sort_scene_text);
            interruptView = findViewById(R.id.interrupt_view);
            interruptTime = findViewById(R.id.interrupt_time);
            cancelImageView = findViewById(R.id.btn_interrupt_cancel);
            addView = findViewById(R.id.add_scene_view);
        }

        @Override
        public void onClick(View view) {
            SceneBean data = (SceneBean) itemView.getTag();
            //可选中状态item和checkbox都可用点击选中
            if (isSelectAct) {
                int position = getViewHolderPosition();
                if (position < 0 || position >= getItemCount()) {
                    return;
                }
                if (view == itemView) {
                    checkbox.setChecked(!checkbox.isChecked());
                }
                if (isSingleSelect) {
                    if(checkbox.isChecked()){
                        for (int i = 0; i < getData().size(); i++) {
                            SceneBean scene = getData().get(i);
                            if (selected.get(scene.getSceneSerialNo()) != null) {
                                selected.clear();
                                notifyItemChanged(i, "updateSingleSelect");
                            }
                        }
                        selected.clear();
                        selected.put(data.getSceneSerialNo(), data);
                    }
                } else {
                    if (checkbox.isChecked()) {
                        if (maxSelectCount > 0 && selected.size() == maxSelectCount) {
                            checkbox.setChecked(false);
                        } else {
                            selected.put(data.getSceneSerialNo(), data);
                        }
                    } else {
                        selected.remove(data.getSceneSerialNo());
                    }
                }
                if (getChildClickListeners() != null) {
                    OnChildClickListener listener = getChildClickListeners().get(checkbox.getId());
                    if (listener != null) {
                        listener.onChildClick(getRecyclerView(), checkbox, position);
                    }
                }
            }else{
                super.onClick(view);
            }
        }

        @Override
        public void onBindView(int position) {
            SceneBean scene = getItem(position);
            itemView.setTag(scene);
            if(scene.getSceneSerialNo() == null){
                addView.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
            }else{
                addView.setVisibility(View.GONE);
                contentView.setVisibility(View.VISIBLE);
                tvName.setText(scene.getName());
                if(selected.get(scene.getSceneSerialNo()) != null){
                    if(bingingType == 3){
                        contentView.setSelected(true);
                        vDelete.setVisibility(View.VISIBLE);
                    }else{
                        checkbox.setChecked(true);
                    }
                }else{
                    if(bingingType == 3){
                        contentView.setSelected(false);
                        vDelete.setVisibility(View.GONE);
                    }else{
                        checkbox.setChecked(false);
                    }
                }
                if (isSelectAct){
                    checkbox.setVisibility(View.VISIBLE);
                    vSetting.setVisibility(View.GONE);
                    if(isSingleSelect){
                        checkbox.setCompoundDrawablesWithIntrinsicBounds(R.drawable.theme_single_check, 0, 0, 0);
                    }else{
                        checkbox.setCompoundDrawablesWithIntrinsicBounds(R.drawable.theme_multiple_check, 0, 0, 0);
                    }
                }else if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
                    vSetting.setVisibility(View.GONE);
                    checkbox.setVisibility(View.GONE);
                }else {
                    checkbox.setVisibility(View.GONE);
                    vSetting.setVisibility(View.VISIBLE);
                }
                tvCommonFlag.setVisibility(scene.getIsFavourite() ? View.VISIBLE : View.GONE);
                if (showFloorRoom){
                    if(scene.getLinkType() == 3){
                        floorRoomName.setText(scene.getFloorName());
                    }else{
                        floorRoomName.setText(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(scene.getRoomSerialNo()));
                    }
                    floorRoomName.setVisibility(View.VISIBLE);
//                if (2 == scene.getLinkType()){
//                    floorRoomName.setText("通用");
//                }else if (0 == scene.getLinkType()){
//                    floorRoomName.setText("默认");
//                }else if (1 == scene.getLinkType()){
//                    floorRoomName.setText(scene.getRoomName());
//                }

                }else {
                    floorRoomName.setVisibility(View.GONE);
                }
//            GlideApp.with(icon).load(scene.getImage()).into(icon);
                String staticImage = scene.getImage();
                icon.setImageURI(staticImage);
                if(!showSettingButton){
                    vSetting.setVisibility(View.GONE);
                }
                if(bingingType == 2 && scene.getTemporary() != null){
                    sortText.setText(scene.getTemporary().toString());
                    sortAction.setVisibility(View.VISIBLE);
                }else{
                    sortAction.setVisibility(View.GONE);
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(scene.getActionSettingExpireTime() != null && !scene.getActionSettingExpireTime().equals("")){
                    try {
                        Date date = format.parse(scene.getActionSettingExpireTime());
                        Date curDate = new Date(System.currentTimeMillis());
                        long time = date.getTime() - curDate.getTime();
                        if(time > 0){
                            interruptView.setVisibility(View.VISIBLE);

                            interruptTime.setText(String.format("%02d:%02d:%02d",time/1000/3600,time/1000%3600/60,time/1000%60));
                            timerGo(time,position);
                        }else{
                            interruptView.setVisibility(View.GONE);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else{
                    interruptView.setVisibility(View.GONE);
                }
            }
        }

        public void timerGo(long time,int position){
            timer = new CountDownTimer(time , 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    interruptTime.setText(String.format("%02d:%02d:%02d",millisUntilFinished/1000/3600,millisUntilFinished/1000%3600/60,millisUntilFinished/1000%60));
                }

                @Override
                public void onFinish() {
                    interruptView.setVisibility(View.GONE);
                }
            }.start();
        }
    }

    @Override
    public void onBindViewHolder(@NonNull BaseAdapter<?>.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        if(payloads != null && payloads.size() > 0){
            if("updateSingleSelect".equals(payloads.get(0))){
                SceneBean scene = getItem(position);
                if(selected.get(scene.getSceneSerialNo()) != null){
                    ((ViewHolder)holder).checkbox.setChecked(true);
                }else{
                    ((ViewHolder)holder).checkbox.setChecked(false);
                }
            }
        }else{
            super.onBindViewHolder(holder, position, payloads);
        }
    }

    public ArrayList<SceneBean> getSelectedData() {
        ArrayList<SceneBean> checkList = new ArrayList<>();
        for(String key : selected.keySet()){
            checkList.add(selected.get(key));
        }
        return checkList;
    }

    public void addSelected(SceneBean selected){
        if(selected != null){
            this.selected.put(selected.getSceneSerialNo(), selected);
        }

        notifyDataSetChanged();
    }

    public void checkSelected(List<SceneBean> selected){
        selected.clear();
        if(selected != null){
            for(SceneBean data : selected){
                this.selected.put(data.getSceneSerialNo(), data);
            }
        }
        notifyDataSetChanged();
    }

    public void checkSelectedSerialNos(List<String> selectedSerialNos){
        selected.clear();
        if(selectedSerialNos != null && getData() != null && getData().size() > 0){
            for(String serialNo : selectedSerialNos){
                for(SceneBean sceneBean : getData()){
                    if(sceneBean.getSceneSerialNo().equals(serialNo)){
                        selected.put(serialNo, sceneBean);
                        break;
                    }
                }
            }
            notifyDataSetChanged();
        }
    }

    public void removeSelected(String deviceSerialNo){
        if(selected != null){
            this.selected.remove(deviceSerialNo);
            notifyDataSetChanged();
        }
    }

//    public void setSelected(List<SceneBean> selected){
//        if(selected != null){
//            for(SceneBean data : selected){
//                this.selected.put(data.getSerialNo(), data);
//            }
//        }
//    }

    public void clearSelected(){
        selected.clear();
    }

    public void checkAll(boolean checked){
        if(checked){
            for(SceneBean data : getData()){
                selected.put(data.getSceneSerialNo(), data);
            }
        }else{
            selected.clear();
        }
        notifyDataSetChanged();
    }

    @Override
    public long getItemId(int position) {
        return getData().get(position).getId();
    }

    public void update(SceneBean newScene) {
        //从1开始, 第0个是场景列表
        for (int i = 1; i < getData().size(); i++) {
            SceneBean scene = getData().get(i);
            if (!TextUtils.isEmpty(scene.getSceneSerialNo()) && scene.getSceneSerialNo().equals(newScene.getSceneSerialNo())) {
                if(!scene.getImage().equals(newScene.getImage())
                        || !scene.getName().equals(newScene.getName())
                        || scene.getIsFavourite() != newScene.getIsFavourite()
                        || !scene.getRoomSerialNo().equals(newScene.getRoomSerialNo())){
                    getData().set(i, newScene);
                    notifyItemChanged(i);
                }
                break;
            }
        }
    }

    public void cancelTimer(){
        if(timer != null){
            timer.cancel();
        }
    }
}